package com.example.swim.controller;


import com.example.swim.Pojo.Apply;
import com.example.swim.Pojo.ClassRoom;
import com.example.swim.Pojo.Coach;
import com.example.swim.Pojo.Student;
import com.example.swim.Service.ApplyService;
import com.example.swim.Service.ClassRoomService;
import com.example.swim.Service.CoachService;
import com.example.swim.Service.StudentService;
import com.example.swim.Utils.R;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author LiYa
 * @create 2022-07-30 11:02
 */
@RestController
@RequestMapping("/Coach")
public class CoachController {
    @Autowired
    CoachService coachService;
    @Autowired
    StudentService studentService;
    @Autowired
    ClassRoomService classRoomService;
    @Autowired
    ApplyService applyService;
    @RequestMapping("/log")
    public String log()
    {
        return "LogCoach";
    }
    @PostMapping("/toMain")
    public R tomain(Coach loginForm)
    {
        HashMap<String,Object> map=new HashMap<>();
        Coach coach;
        if (loginForm!=null) {
            if ((coach = coachService.findCoach(loginForm)) != null)
            {
                map.put("user", coach);
                map.put("identity", "coach");
                return new R(true,map);
            }
        }
       map.put("msg","用户名或密码错误，有问题去找管理员" );
//        用跳转是为了将msg内容放到页面中去
        return new R(false,map);
    }

//    学员管理页面 主页面
    @PostMapping ("/main")
    public R Main(Coach coach)
    {
        System.out.println(coach.getId());
        List<ClassRoom> classRooms= classRoomService.findByCoach_id(coach);
        HashMap<String,Object>map=new HashMap<>();
        map.put("coach", coach);
        map.put("classRooms", classRooms);
        return new R(true,map);
    }
//    学员添加
    @RequestMapping("/insert")
    public R insert(Student student)
    {
        student.setFirst(0);
        studentService.insert(student);
        return new R(true,"学员添加成功");
    }
//    学员删除
    @GetMapping("/del")
    public R del(@RequestParam Integer id)
    {
        studentService.del(id);
        return  new R(true, "删除成功");
    }
//    学员更新
    @PostMapping("updateStu")
    public R UpdateStu(Student student,Model model)
    {
        model.addAttribute("success", "成功更改id为：" +student.getId());
        studentService.update(student);
        return new R(true,"修改成功");
    }
//    报名审核
    @GetMapping("/check")
    public R Check(@RequestParam int id)
    {
        List<Apply> applies=applyService.find(id);
        if(applies.isEmpty()){
            return new R(false,applies);
        }
        return new R(true,applies);
    }
//    提交报名
    @RequestMapping("app")
    public R Apply(Apply apply,Student student)
    {
        studentService.insertNew(student);
        applyService.del(apply);
       return new R(true,"报名成功");
    }
//    个人主页
    @GetMapping("/Mine")
    public R Mine(int id)
    {
        Coach coach=coachService.findCoach(id);
       return new R(true,coach);
    }
//    个人主页更新
    @RequestMapping("update")
    public R updateMine(Coach coach)
    {
        coachService.updateCoach(coach);
        return new R(true,"修改信息成功");
    }


    @ResponseBody
    @RequestMapping(value = "inputExcel",method = RequestMethod.POST)
    public R getExcel(@RequestParam("file") MultipartFile file) throws Exception
    {
        if(!file.isEmpty())
        {
            System.out.println("正在上传");
            studentService.importExcel(file);
        }
        return new R(true,"导入教练成功");
    }
    @RequestMapping("/down")
    public String down(@RequestParam String downName,HttpServletRequest request,HttpServletResponse response)
    {
        String downPath="E:\\大三_上\\JAVAEE\\Student.xlsx";
        FileInputStream in=null;//输入流
        ServletOutputStream out=null;
        try{
//            设置下载文件使用的报头
            response.setHeader("Content-Type","application/x-msdownload");
            response.setHeader("content-Disposition", "attachment;filename="
                    +toUTF8String(downName));
            in=new FileInputStream("E:\\大三_上\\JAVAEE\\下载");
            out=response.getOutputStream();
            out.flush();
            int read=0;
            byte b[]=new byte[1024];
            while((read=in.read())!=-1&in!=null)
            {
                out.write(b,0,read);
            }
            out.flush();
            in.close();
            out.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }
    public String toUTF8String(String str) {
        StringBuffer sb = new StringBuffer();
        int len = str.length();
        for (int i = 0; i < len; i++) {
            char c = str.charAt(i);
            if (c >= 0 && c <= 255) {
                sb.append(c);
            } else {
                byte b[];
                try {
                    b = Character.toString(c).getBytes("UTF-8");
                } catch (Exception e) {
                    e.printStackTrace();
                    ;
                    b = null;
                }
                for (int j = 0; j < b.length; j++) {
                    int k = b[j];
                    if (k < 0) {
                        k &= 255;
                    }
                    sb.append("%" + Integer.toHexString(k).toUpperCase());
                }
            }
        }
        return sb.toString();
    }
}
